package com.it00zyq.admin.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it00zyq.admin.service.MailService;
import com.it00zyq.common.entity.Schedule;
import com.it00zyq.common.enums.ScheduleEnum;
import com.it00zyq.common.mapper.ScheduleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author zyq
 * @Date 2022/5/3 11:25
 * @Description TODO
 * @Version 1.0
 **/
@Configuration
@EnableScheduling
@Slf4j
@RequiredArgsConstructor
public class TimeTask {
    private final ScheduleMapper mapper;
    private final MailService service;

    @Scheduled(cron = "0 0 22 ? * *")
    public void Task1() {
        doWork();
    }

    @Scheduled(cron = "0 0 8 ? * *")
    public void Task2() {
        doWork();
    }


    private void doWork() {
        QueryWrapper<Schedule> wrapper = new QueryWrapper<>();
        wrapper.eq("state", ScheduleEnum.PROCESSING.getCode());
        List<Schedule> schedules = mapper.selectList(wrapper);
        DateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

        String TO_MAIL = "it00zyq@sina.com";
        String subject = "O(∩_∩)O 日程提醒";
        StringBuilder content = new StringBuilder();
        content.append("=================================================").append("\n");
        content.append("日程进行数: ").append(schedules.size()).append("\n");
        for (Schedule schedule : schedules) {
            content.append("=================================================").append("\n");
            content.append("日程内容: ").append(schedule.getContent()).append("\n");
            content.append("截止时间: ").append(format.format(schedule.getEstimatedTime())).append("\n");
        }
        content.append("=================================================").append("\n");

        service.sendMail(subject, content.toString(), TO_MAIL);
        log.info("【日程提醒邮件发送】: {}", schedules.size());
    }

}
